package org.swxjava.assembler;

import java.util.zip.Deflater;

public class Compressor {

	public static final int NO_COMPRESSION_LEVEL = 0;
	public static final int DEFAULT_COMPRESSION_LEVEL = 4;
	public static final int NAX_COMPRESSION_LEVEL = 9;

	public static byte[] compress(byte[] bytes, int length, int compressionLevel) {
		if (compressionLevel == NO_COMPRESSION_LEVEL) {
			// do nothing
			return bytes;
		}
		byte[] compressed = null;
		byte[] temp = new byte[length];

		Deflater deflater = new Deflater(compressionLevel);
		deflater.setInput(bytes, 8, length - 8);
		deflater.finish();

		int compressedLength = deflater.deflate(temp);
		compressed = new byte[compressedLength + 8];

		// the first 8 bytes of the header are uncompressed
		System.arraycopy(bytes, 0, compressed, 0, 8);

		// copy the compressed data from the temporary byte array to its new
		// byte array
		System.arraycopy(temp, 0, compressed, 8, compressedLength);

		// the first byte of the swf indicates whether the swf is compressed or
		// not
		compressed[0] = Constants.COMPRESSED_SWF;

		// make sure the swf size structure represents the uncompressed size of
		// the swf
		int bl = bytes.length;
		compressed[4] = (byte) (bl & 0x000000FF);
		compressed[5] = (byte) ((bl & 0x0000FF00) >> 8);
		compressed[6] = (byte) ((bl & 0x00FF0000) >> 16);
		compressed[7] = (byte) ((bl & 0xFF000000) >> 24);

		return compressed;
	}
}
